package com.eclipse.e0113_网络编程.模拟浏览器发送请求;





import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCUtils {

	private static String url = "jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&rewriteBatchedStatements=true";

	private static String userName = "root";

	private static String password = "qq123123";

	/**
	 * 执行insert、update、delete
	 * 
	 * @param sql
	 * @param params
	 */
	public static void update(String sql, Object... params) {
		Connection connection = getConnection();

		PreparedStatement statement = null;
		try {
			statement = connection.prepareStatement(sql);

			for (int i = 0; i < params.length; i++) {
				statement.setObject(i + 1, params[i]);
			}

			statement.executeUpdate();
		} catch (SQLException ex) {
			throw new RuntimeException("执行的SQL有问题：" + sql, ex);
		} finally {
			closeResourec(connection, statement, null);
		}
	}

	/**
	 * 关闭资源
	 * 
	 * @param connection
	 * @param statement
	 * @param resultSet
	 */
	public static void closeResourec(Connection connection, Statement statement, ResultSet resultSet) {
		try {
			if (resultSet != null) {
				resultSet.close();
			}
			if (statement != null) {
				statement.close();
			}
			if (connection != null) {
				connection.close();
			}
		} catch (SQLException ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 打开连接
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Connection getConnection() {
		try {
			// 1:加载驱动类
			Class.forName("com.mysql.cj.jdbc.Driver");

			// 2: 打开连接
			Connection connection = DriverManager.getConnection(url, userName, password);
			return connection;
		} catch (ClassNotFoundException ex) {
			throw new RuntimeException("数据库驱动没导入", ex);
		} catch (SQLException ex) {
			throw new RuntimeException("url或者用户名或者密码是错误", ex);
		}
	}
}

